package com.example.administrator.exkotlin.jetpack.workmanager

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.work.*
import com.example.administrator.exkotlin.R
import com.example.administrator.exkotlin.jetpack.workmanager.work.SimpleWork
import kotlinx.android.synthetic.main.activity_work_manager.*
import java.util.concurrent.TimeUnit

class WorkManagerActivity : AppCompatActivity() {

    private val TAG = "WorkManagerActivity"
    private lateinit var workRequest: WorkRequest
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_work_manager)
        initData()
    }

    private fun initData() {
        btn_simple_work.setOnClickListener {
            workRequest = OneTimeWorkRequest.Builder(SimpleWork::class.java).apply {
                //设置延迟执行时间，自定义单位，时分秒日
                setInitialDelay(5, TimeUnit.SECONDS)
                //添加 tag、可以在enqueue后，取消执行，也可以使用request.id来取消
                addTag("workRequest")

                //设置任务失败，返回Result.retry 的时候，
                // 下次执行的设置 parm1： 指数或者线性间隔，parm2：下次执行时间（最短十秒），parm3：下次执行时间单位
                setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)

            }.build()
            WorkManager.getInstance(this).enqueue(workRequest)


            //监听任务执行的结果
            WorkManager.getInstance(this).getWorkInfoByIdLiveData(workRequest.id).observe(this, Observer { data ->
                if (data.state == WorkInfo.State.SUCCEEDED) {

                    Log.i(TAG, "${data.id}成功")
                } else if (data.state == WorkInfo.State.FAILED) {
                    Log.i(TAG, "${data.id}失败")
                }
            })
        }

        btn_cancel_work.setOnClickListener {
            WorkManager.getInstance(this).cancelAllWorkByTag("workRequest")
//            WorkManager.getInstance(this).cancelWorkById(workRequest.id)
//            WorkManager.getInstance(this).cancelAllWork()
        }




    }
}
